package com.heima.juc.unlock;

import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : leimingchao
 * @date Date : 2022年02月12日 15:30
 */
@Slf4j(topic = "c.TestAccount")
public class TestAccount {

    public static void main(String[] args) {
        Account account = new AccountUnsafe(10000);
        Account.demo(account);
    }
}

class AccountUnsafe implements Account {

    private Integer balance;

    public AccountUnsafe(Integer balance) {
        this.balance = balance;
    }

    @Override
    public Integer getBalance() {
        synchronized (this) {

            return this.balance;
        }
    }

    @Override
    public void withdraw(Integer amount) {
        synchronized (this) {

            this.balance -= amount;
        }
    }
}

interface Account {

    /**
     * 获得余额
     */
    Integer getBalance();

    void withdraw(Integer amount);

    /**
     * 方法内会启动1000个线程，每个线程做 - 10 元的操作
     * 如果初始余额为10000 那么正确的结果应当是 0
     * @param account
     */
    static void demo(Account account) {

        List<Thread> ts = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withdraw(10);
            }));

        }

        LocalDateTime start = LocalDateTime.now();

        ts.forEach(Thread::start);

        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        LocalDateTime end = LocalDateTime.now();

        System.out.println(account.getBalance() + " cost: " + Duration.between(start, end).toMillis() + " ms");
    }
}
